<template>
    <div>
        <div class="container loginIn">
            <div class="left center">
                <el-form class="login-form" label-position="left">
                    <div class="title-container">
                        <h3 class="title">物流管理系统</h3>
                    </div>
                    <el-form-item>
                        <span class="svg-container"><svg-icon icon-class="user" /></span>
                        <el-input placeholder="请输入账号" name="username" type="text" v-model="rulesForm.username" />
                    </el-form-item>
                    <el-form-item>
                        <span class="svg-container"><svg-icon icon-class="password" /></span>
                        <el-input placeholder="请输入密码" name="password" type="password" v-model="rulesForm.password" />
                    </el-form-item>
                    <el-form-item>
                        <span class="svg-container"><svg-icon icon-class="peoples" /></span>
                        <el-select 
                            v-model="rulesForm.role" 
                            placeholder="请选择角色"
                            style="width: 63%; margin-left: 5%;">
                            <el-option
                                v-for="item in filteredMenus"
                                :key="item.roleName"
                                :label="item.roleName"
                                :value="item.roleName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-button type="primary" @click="showVerifyCodeDialog" class="loginInBt">登录</el-button>
                    <el-form-item class="setting">
                        <div class="forget" @click="forget('yonghu')">忘记密码</div>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 验证码弹窗 -->
        <el-dialog
            title="验证码"
            :visible.sync="verifyCodeDialogVisible"
            width="40%"
            :close-on-click-modal="false"
            :show-close="true"
            center>
            <div class="verify-code-container">
                <div class="code-display">
                    <canvas ref="verifyCanvas" width="300" height="100"></canvas>
                </div>
                <el-input 
                    v-model="rulesForm.code" 
                    placeholder="请输入验证码" 
                    style="margin-top: 20px;"
                    @keyup.enter.native="verifyAndLogin">
                </el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="refreshVerifyCode">刷新验证码</el-button>
                <el-button type="primary" @click="verifyAndLogin">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import menu from "@/utils/menu";
export default {
    data() {
        return {
            rulesForm: {
                username: "",
                password: "",
                role: "",
                code: '',
                rememberMe: false,
            },
            menus: [],
            tableName: "",
            codes: [{
                num: 1,
                color: '#000',
                rotate: '10deg',
                size: '16px'
            }, {
                num: 2,
                color: '#000',
                rotate: '10deg',
                size: '16px'
            }, {
                num: 3,
                color: '#000',
                rotate: '10deg',
                size: '16px'
            }, {
                num: 4,
                color: '#000',
                rotate: '10deg',
                size: '16px'
            }, {
                num: 5,
                color: '#000',
                rotate: '10deg',
                size: '16px'
            }, {
                num: 6,
                color: '#000',
                rotate: '10deg',
                size: '16px'
            }],
            verifyCodeDialogVisible: false,
            codeExpireTime: 180,
            expireTimer: null,
        };
    },
    mounted() {
        let menus = menu.list();
        this.menus = menus;
        this.$nextTick(() => {
            this.checkRememberedUser();
        });
    },
    created() {
        this.setInputColor();
        this.getRandCode();
        this.checkRememberedUser();
    },
    methods: {
        setInputColor() {
            this.$nextTick(() => {
                document.querySelectorAll('.loginIn .el-input__inner').forEach(el => {
                    el.style.backgroundColor = "rgba(255, 255, 255, 1)"
                    el.style.color = "rgba(51, 51, 51, 1)"
                    el.style.height = "44px"
                    el.style.lineHeight = "44px"
                    el.style.borderRadius = "4px"
                })
                document.querySelectorAll('.loginIn .style3 .el-form-item__label').forEach(el => {
                    el.style.height = "44px"
                    el.style.lineHeight = "44px"
                })
                document.querySelectorAll('.loginIn .el-form-item__label').forEach(el => {
                    el.style.color = "rgba(238, 238, 238, 1)"
                })
                setTimeout(() => {
                    document.querySelectorAll('.loginIn .role .el-radio__label').forEach(el => {
                        el.style.color = "#fff"
                    })
                }, 350)
            })

        },
        register(tableName) {
            this.$storage.set("loginTable", tableName);
            this.$router.push({ path: '/register' })
        },
        forget(tableName) {
            this.$notify.error({
                title: '错误',
                message: '请及时联系管理员进行修改',
                duration: 2000
            });
        },
        checkRememberedUser() {
            const rememberedUser = this.$storage.getRememberedUser();
            if (rememberedUser) {
                this.rulesForm.username = rememberedUser.username;
                this.rulesForm.password = rememberedUser.password;
                this.rulesForm.role = rememberedUser.role;
                this.rulesForm.rememberMe = true;
            }
        },
        drawVerifyCode() {
            if (!this.$refs.verifyCanvas) return;
            
            const canvas = this.$refs.verifyCanvas;
            const ctx = canvas.getContext('2d');
            
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 设置背景色
            ctx.fillStyle = '#f5f5f5';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制干扰线
            for (let i = 0; i < 5; i++) {
                ctx.strokeStyle = this.getRandomColor();
                ctx.beginPath();
                ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.stroke();
            }
            
            // 绘制干扰点
            for (let i = 0; i < 50; i++) {
                ctx.fillStyle = this.getRandomColor();
                ctx.beginPath();
                ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI);
                ctx.fill();
            }
            
            // 绘制验证码
            const code = this.codes.map(item => item.num).join('');
            ctx.font = 'bold 40px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            
            // 计算总宽度和起始位置
            const totalWidth = code.length * 45;
            const startX = (canvas.width - totalWidth) / 2 + 22.5;
            
            for (let i = 0; i < code.length; i++) {
                ctx.fillStyle = this.getRandomColor();
                ctx.save();
                ctx.translate(startX + i * 45, 50);
                ctx.rotate((Math.random() - 0.5) * 0.5);
                ctx.fillText(code[i], 0, 0);
                ctx.restore();
            }

            // 自动复制验证码到剪贴板
            navigator.clipboard.writeText(code).catch(err => {
                console.error('复制验证码失败:', err);
            });
        },
        getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        },
        refreshVerifyCode() {
            this.getRandCode();
            this.$nextTick(() => {
                this.drawVerifyCode();
            });
        },
        showVerifyCodeDialog() {
            if (!this.rulesForm.username) {
                this.$message.error("请输入用户名");
                return;
            }
            
            if (!this.rulesForm.password) {
                this.$message.error("请输入密码");
                return;
            }

            if (!this.rulesForm.role) {
                this.$message.error("请选择角色");
                return;
            }

            this.getRandCode();
            this.$nextTick(() => {
                this.drawVerifyCode();
            });
            this.verifyCodeDialogVisible = true;
        },
        verifyAndLogin() {
            if (!this.rulesForm.code) {
                this.$message.error("请输入验证码");
                this.getRandCode();
                this.$nextTick(() => {
                    this.drawVerifyCode();
                });
                return;
            }

            const verifyCode = this.codes.map(item => item.num).join('');
            const inputCode = this.rulesForm.code.trim();
            
            if (inputCode.toLowerCase() !== verifyCode.toLowerCase()) {
                this.$message.error("验证码输入有误");
                this.getRandCode();
                this.$nextTick(() => {
                    this.drawVerifyCode();
                });
                return;
            }

            // 处理记住密码逻辑
            if (this.rulesForm.rememberMe) {
                this.$storage.saveRememberedUser(
                    this.rulesForm.username,
                    this.rulesForm.password,
                    this.rulesForm.role
                );
            } else {
                this.$storage.removeRememberedUser();
            }
            
            this.verifyCodeDialogVisible = false;
            this.login();
        },
        getRandCode(len = 6) {
            this.randomString(len);
        },
        randomString(len = 6) {
            let chars = [
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
                "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
                "3", "4", "5", "6", "7", "8", "9"
            ]
            let colors = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
            let sizes = ['14', '15', '16', '17', '18']

            let hasNumber = false;
            let hasLetter = false;
            let output = [];
            
            for (let i = 0; i < len; i++) {
                let key;
                if (i === len - 2 && !hasNumber) {
                    key = Math.floor(Math.random() * 10) + 52;
                } else if (i === len - 1 && !hasLetter) {
                    key = Math.floor(Math.random() * 52);
                } else {
                    key = Math.floor(Math.random() * chars.length);
                }
                
                this.codes[i].num = chars[key];
                
                if (key >= 52) hasNumber = true;
                if (key < 52) hasLetter = true;
                
                let code = '#';
                for (let j = 0; j < 6; j++) {
                    let colorKey = Math.floor(Math.random() * colors.length);
                    code += colors[colorKey];
                }
                this.codes[i].color = code;
                
                let rotate = Math.floor(Math.random() * 45);
                let plus = Math.floor(Math.random() * 2);
                if (plus == 1) rotate = '-' + rotate;
                this.codes[i].rotate = 'rotate(' + rotate + 'deg)';
                
                let size = Math.floor(Math.random() * sizes.length);
                this.codes[i].size = sizes[size] + 'px';
            }
        },
        // 登陆
        login() {
            let menus = this.menus;
            for (let i = 0; i < menus.length; i++) {
                if (menus[i].roleName == this.rulesForm.role) {
                    this.tableName = menus[i].tableName;
                }
            }
            
            this.$http({
                url: `${this.tableName}/login?username=${this.rulesForm.username}&password=${this.rulesForm.password}`,
                method: "post"
            }).then(({ data }) => {
                if (data && data.code === 0) {
                    // 保存用户信息
                    this.$storage.set("Token", data.token);
                    this.$storage.set("userId", data.userId);
                    this.$storage.set("role", this.rulesForm.role);
                    this.$storage.set("sessionTable", this.tableName);
                    this.$storage.set("adminName", this.rulesForm.username);
                    
                    // 跳转到首页
                    this.$router.replace({ path: "/index/" });
                } else {
                    this.$message.error(data.msg);
                }
            });
        },
    },
    computed: {
        filteredMenus() {
            return this.menus.filter(item => item.hasBackLogin === '是');
        },
    },
    beforeDestroy() {
        if (this.expireTimer) {
            clearTimeout(this.expireTimer);
        }
    },
    watch: {
        verifyCodeDialogVisible(newVal) {
            if (newVal) {
                this.$nextTick(() => {
                    this.drawVerifyCode();
                });
            } else {
                // 关闭弹窗时清空验证码输入框
                this.rulesForm.code = '';
            }
        },
        'rulesForm.rememberMe': {
            handler(newVal) {
                if (!newVal) {
                    // 取消勾选记住密码时清除保存的凭据
                    this.$storage.removeRememberedUser();
                }
            },
            immediate: true
        }
    },
};
</script>
<style lang="scss" scoped>
.loginIn {
    min-height: 100vh;
    position: relative;
    background-color: #def0ff;
    background-size: cover;

    .left {
        position: absolute;
        left: 0;
        top: 0;
        width: 620px;
        height: 100%;
        background-color: rgba(208, 163, 140, 0.53);

        &.center {
            left: 50%;
            top: 50%;
            transform: translate3d(-50%, -50%, 0);
            height: 446px;
            border-radius: 8px;
        }

        &.right {
            left: inherit;
            right: 0;
        }

        .login-form {
            background-color: #fff;
            width: 100%;
            padding: 0 12px;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            flex-direction: column;

            .title-container {
                text-align: center;
                font-size: 24px;

                .title {
                    color: rgba($color: #3c3c3c, $alpha: 1);
                    margin: 20px 0;
                }
            }

            .el-form-item {
                width: 80%;
                margin: 10px auto;
                position: relative;

                .svg-container {
                    scale: 1.2;
                    padding: 0;
                    color: #889aa4;
                    position: absolute;
                    left: -20px;
                    top: 60%;
                    transform: translateY(-50%);
                    z-index: 2;
                }

                .el-input {
                    margin-left: 5%;
                    width: 95%;

                    input {
                        border: 1px solid #dcdfe6;
                        border-radius: 4px;
                        background: transparent;
                        padding-left: 45px !important;
                        height: 32px;
                        line-height: 32px;

                        &:focus {
                            border-color: #409EFF;
                        }
                    }
                }
            }

            /deep/ .svg-icon {
                width: 18px;
                height: 18px;
            }

            .el-select .el-input input {
                color: #333;
            }

            .loginInBt {
                width: 80%;
                height: 44px;
                line-height: 44px;
                margin: 0 auto;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 16px;
                border-radius: 4px;
                background-color: #408aff;
                border-color: rgba(255, 216, 103, 0.64);
                color: #fff;
            }

            .setting {
                & /deep/ .el-form-item__content {
                    padding: 0 15px;
                    box-sizing: border-box;
                    line-height: 32px;
                    height: 32px;
                    font-size: 14px;
                    color: #999;
                    margin: 0;

                    .register {
                        float: left;
                        color: #333;
                    }

                    .forget {
                        float: right;
                        color: #333;
                        cursor: pointer;

                        &:hover {
                            color: #409EFF;
                        }
                    }

                    .reset {
                        float: right;
                        width: 50%;
                        text-align: right;
                        color: #fff;
                    }
                }
            }

            input::-webkit-input-placeholder {
                padding-left: 8px;
            }

            input::-moz-placeholder {
                padding-left: 8px;
            }

            input:-ms-input-placeholder {
                padding-left: 8px;
            }

            /deep/ .el-select {
                .el-input {
                    input {
                        border: 1px solid #dcdfe6;
                        border-radius: 4px;
                        background: transparent;
                        height: 44px;
                        line-height: 44px;
                        text-align: center;
                        
                        &:focus {
                            border-color: #409EFF;
                        }
                    }
                }
                
                .el-select__caret {
                    color: #889aa4;
                    line-height: 44px;
                    right: 15px;
                }
            }
            
            /deep/ .el-select-dropdown__item {
                padding: 0 20px;
                text-align: center;
                
                &.selected {
                    color: #409EFF;
                }
                
                &:hover {
                    background-color: #f5f7fa;
                }
            }
        }
    }

    .code {
        .el-form-item__content {
            position: relative;

            .getCodeBt {
                position: absolute;
                right: 0;
                top: 0;
                width: 100px;
                height: 40px;
                line-height: 40px;
                background-color: rgba(51, 51, 51, 0.4);
                color: #fff;
                text-align: center;
                border-radius: 0 4px 4px 0;
                overflow: hidden;

                span {
                    padding: 0 5px;
                    display: inline-block;
                    font-size: 16px;
                    font-weight: 600;
                }
            }
        }
    }

    .style2 {
        padding-left: 30px;

        .svg-container {
            left: -30px !important;
        }

        .el-input {
            & /deep/ input {
                padding: 0 15px !important;
            }
        }
    }

    .code.style2,
    .code.style3 {
        .el-input {
            & /deep/ input {
                padding: 0 115px 0 15px;
            }
        }
    }

    .style3 {
        & /deep/ .el-form-item__label {
            padding-right: 6px;
        }

        .el-input {
            & /deep/ input {
                padding: 0 15px !important;
            }
        }
    }

    .role {
        & /deep/ .el-form-item__label {
            width: 56px !important;
        }

        & /deep/ .el-radio {
            margin-right: 12px;
            color: #000 !important;
        }

        /deep/ .el-radio {
            .el-radio__label {
                color: #333 !important;
                font-size: 14px;
            }

            &.is-checked .el-radio__label {
                color: #409EFF !important;
            }
        }
    }
}

.verify-code-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .code-display {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        height: 100px;
        background-color: #f5f5f5;
        padding: 0;
        border-radius: 4px;
        overflow: hidden;
    }
}
</style>
